package com.cmy.scheduleLite.utils;

import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import lombok.extern.slf4j.Slf4j;

import java.time.ZonedDateTime;
import java.util.Optional;

/**
 * @author : Cmy
 * @date : 2025-04-09 11:13
 */
@Slf4j
public class CronUtils {


    public static boolean isTimeSpanTooLongCron(String cronExpression) {
        try {
            // 解析 cron 表达式
            CronDefinition definition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
            CronParser parser = new CronParser(definition);
            Cron cron = parser.parse(cronExpression);

            // 计算下一次执行时间
            ExecutionTime executionTime = ExecutionTime.forCron(cron);
            ZonedDateTime now = ZonedDateTime.now();

            Optional<ZonedDateTime> nextExecution = executionTime.nextExecution(now);

            if (nextExecution.isPresent()) {
                ZonedDateTime tenYearsLater = now.plusYears(10);
                return nextExecution.get().isAfter(tenYearsLater);
            } else {
                return true;
            }
        } catch (Exception e) {
            // 表达式格式错误，视为无效任务
            return true;
        }
    }
}

    